<?php

namespace common\components\api_tool;

use Carbon\Carbon;
use common\components\wtools\tools\ArrayHelper;
use common\models\db\MpUsers;
use common\Tools;
use GuzzleHttp\Client;

class XcxApi extends ApiTool
{
    public $jwtTokenInfo;

    /**
     * @param array $jwtTokenArr
     * @return $this
     * @throws \Exception
     */
    public function setJwtToken($jwtTokenArr)
    {
        $this->jwtTokenInfo = MpUsers::getJwtToken($jwtTokenArr);
        return $this;
    }

    /**
     * @param $uri
     * @param $form_params
     * @return mixed
     */
    public function guestPost($uri, $form_params = []) {
        return $this->post($uri, $form_params, false);
    }

    /**
     * @param $uri
     * @param $form_params
     * @param bool $isAuth
     * @return mixed
     * @throws
     */
    public function post($uri, $form_params = [], $isAuth = true)
    {
        $form_params = array_filter($form_params, function ($value) {
            return $value !== null;
        });
        $options = [
            'form_params' => $form_params,
        ];
        return $this->request($uri, $options, 'post', $isAuth);
    }

    public function request($uri = "", $options = [], $method = "post", $isAuth = true)
    {
        $base_uri = $this->getFullUrl($uri);
        $clientOptions = ['base_uri' => $base_uri];
        if (!YII_ENV_PROD) $clientOptions['verify'] = false;
        $client = new Client($clientOptions);
        if ($isAuth) {
            if (!$this->jwtTokenInfo) {
                throw new \Exception("请先设置jwtToken");
            }
            $options['headers'] = [
                'Authorization' => 'Bearer '.$this->jwtTokenInfo['jwt']['jwtToken'],
            ];
            $options['form_params'] = $this->generateFormParams($options['form_params'] ?? []);
            if (isset($options['query'])) {
                $options['query'] = $this->generateFormParams($options['query']);
            }
        }
        $resp = $client->request($method, '', $options);
        $resp_cont = $resp->getBody()->getContents();
        $res = Tools::isJson($resp_cont);
        if (!$res || $res['code'] !== 200) {
            throw new \Exception("请求xcxApi失败：".$res['message'] ?? '');
        }
        return $res['data'];
    }

    /**
     * @param $user
     * @param array $form_params
     * @return array
     */
    public function generateFormParams($form_params = [])
    {
        $jwt = $this->jwtTokenInfo['jwt'];
        $payload = $jwt['payload'];
        $token = $payload['token'];
        $form_params[md5($token)] = $this->jwtTokenInfo['encryptedMpUserKey'];
        $form_params['timestamp'] = Carbon::now()->timestamp;
        $form_params['nonce'] = $form_params['timestamp'].rand(10000000, 40000000);
        $p = $form_params;
        ksort($p);
        unset($p['sign']);
        $p_arr = [];
        foreach ($p as $k => $v) {
            $p_arr[] = $k."=".$v;
        }
        $p_str = ArrayHelper::arr2str($p_arr, '&');
        $form_params['sign'] = md5($p_str);
        return $form_params;
    }

    /**
     * @param $uri
     * @return string
     */
    public function getFullUrl($uri = "")
    {
        return $this->baseUri.'/xcxApi'.$uri;
    }
}
